import React, { useEffect,useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Text, View, Image, getDevInfo, hideMenuButton, openDeviceDetailPage, getWeathers,router } from '@ray-js/ray';
import { NavBar, Button } from '@ray-js/smart-ui';
import { IconFont } from '@/components/icon-font';
import styles from './index.module.less';
import { useActions, useProps } from '@ray-js/panel-sdk';
import { TopBar, Weather } from '@/components';
import { edit, homebg, oil, homebg2, fan, perfume, off, open, more,ic_volume,power_on,power_off,ic_mode,ic_light} from '@/res/index'
import { Circle } from '@ray-js/smart-ui';
import Strings from '@/i18n';
import { AVAILABLE_CAPACITY } from '@/constant';
import { setBtmShow, selectCustom, setWeather } from '@/redux/modules/customSlice';
import { getCachedLaunchOptions } from '@/api/getCachedLaunchOptions';
import { PickerOilPopup ,PickerOilTypePopup} from '@/components';
import { selectAttrs,updateAttrsAsync } from '@/redux/modules/devAtts';

/**
 * Home component that renders the main page of the application.
 * 
 * Features:
 * - Displays a navigation bar with home and timer sections
 * - Includes a content section with a template title and primary button
 * - Handles back navigation via left arrow icon
 * 
 * @returns {JSX.Element} The rendered home page component
 */
export function Home() {
  hideMenuButton();
  const actions = useActions();
  const dispatch = useDispatch();
  const devInfo = getDevInfo();
  const capacity = useProps(props => props.available_capacity)
  const fanSwitch = useProps(props => props.fan_switch)
  const switch_led = useProps(props => props.switch_led)

  const oilSwitch = useProps(props => props.switch)

  const [oilPiackerShow, setOilPiackerShow] = useState<boolean>(false)
  const [aromatherapyShow, setAromatherapyShow] = useState<boolean>(false)
  const { deviceId } = getCachedLaunchOptions().query;
  const devAttrs = useSelector(selectAttrs);
  console.log("devAttrs",devAttrs)
  const mTypes = devAttrs.slice(2);

  useEffect(() => {
    getWeathers({
      devId: deviceId,
      dataRange: 7,
    })
      .then((response) => {
        console.log("天气信息", response);
        dispatch(setWeather(response.weathers))
      })
      .catch();
  }, [])

  function getProCapacity(){
     switch(capacity){
       case "high":
         return 100;
       case "middle":
         return 50;
       case "low":
         return 25
       case "very_low":
         return 5;
     }
  }
  //跳转设备详情页
  const goDetail = () => {
    openDeviceDetailPage({
      deviceId: deviceId,
      success: () => {
      }
    })
  };
  const onOilPiackerConfirm=(time:string)=>{
     dispatch(updateAttrsAsync({ code:"oilTotal", value: time}))
    setOilPiackerShow(false);
  }
  const onAromatherapyConfirm=(time:string)=>{
    dispatch(updateAttrsAsync({ code:"aromatherapyType", value: time}))
    setAromatherapyShow(false);
  }
  function getTypeText(index){
    let item =  mTypes[index]
    return    item.value.length?item.value:Strings.getLang(`oil_type_${index+1}`);
  }
  const rightNode = () => {
    return (
      <View style={{ display: "flex", }}>
        <View style={{ width: "72rpx", height: "64rpx", zIndex: "999", display: "flex", alignItems: "flex-end", justifyContent: "center" }}>
          <Image mode='aspectFit' src={edit} style={{ width: "80rpx", height: "80rpx", verticalAlign: 'bottom', }} onClick={goDetail} />
        </View>

      </View>
    )
  }
  return (
    <View>
      <TopBar title={devInfo?.name}>{rightNode()}</TopBar>

      <View className={styles.view}>
        <View
          className={styles.content}
          onClick={() => {
            // actions.switch_1.toggle();
          }}
        >
          <View className={styles['space-around']} style={{ marginTop: '50rpx' }}>
            <View className={styles.progresslayout} style={{ backgroundImage: `url(${homebg})`, backgroundSize: 'cover' }}>
              <Circle className={styles.progres} size='400rpx' percent={getProCapacity()} style={{ marginBottom: "16rpx" }} maskColor='#E7EAF3' fillColor={`linear-gradient(to right, #53C1DF, #3BAF36)`}>

                <View className={styles.progresText}>
                  <Image src={oil} style={{ width: '43rpx', height: '57rpx', verticalAlign: 'bottom', marginBottom: '10rpx' }}></Image>
                  <Text className={styles.capacityText}>{AVAILABLE_CAPACITY[capacity]}</Text>
                  <Text className={styles.capacityLabel}>{Strings.getLang("remaining_capacity")}</Text>

                </View>
              </Circle>

            </View>
            <View className={styles.Weatherlayout} >
              <Weather />
            </View>

            <View className={styles.zonelayout} >
              <View className={styles.zoneLetf} >
                <Image className={styles.zoneImage} src={fan} />
                <Text className={styles.zoneLetfTextLayout}>{Strings.getLang("fan_switch")}</Text>
              </View>
              <Image mode='aspectFit' className={styles.mSwitch} src={!fanSwitch ? off : open} onClick={() => {
                actions.fan_switch.toggle();
              }} />
            </View>
            <View className={styles.zonelayout} >
              <View className={styles.zoneLetf} >
                <Image className={styles.zoneImage} src={ic_light} />
                <Text className={styles.zoneLetfTextLayout}>{Strings.getLang("light_switch")}</Text>
              </View>
              <Image mode='aspectFit' className={styles.mSwitch} src={!switch_led ? off : open} onClick={() => {
                actions.switch_led.toggle();
              }} />
            </View>

            <View className={styles.zonelayout} onClick={() => {setOilPiackerShow(true)} }>
              <View className={styles.zoneLetf} >
                <Image className={styles.zoneImage} src={ic_volume} />
                <View className={styles.zoneLetfTextLayout}>
                  <Text className={styles.selectText}>{devAttrs[0].value}</Text>
                  <Text className={styles.selectLabel}>{Strings.getLang("total_oils")}</Text>
                </View>

              </View>
              <Image mode='aspectFit' className={styles.more} src={more} onClick={() => {
            
              }} />
            </View>
            <View className={styles.zonelayout} onClick={() => {setAromatherapyShow(true)}} >
              <View className={styles.zoneLetf} >
                <Image className={styles.zoneImage} src={perfume} />
                <View className={styles.zoneLetfTextLayout}>
                  <Text className={styles.selectText} >{getTypeText(parseInt(devAttrs[1].value)) }</Text>
                  <Text className={styles.selectLabel}>{Strings.getLang("aromatherapy_selection")}</Text>
                </View>
              </View>
              <Image mode='aspectFit' className={styles.more} src={more} onClick={() => {
              }} />
            </View>
          </View>
        </View>
      </View>
      <View className={styles.buttomLayout}>
         <View className={styles.buttomBtnLayout} onClick={() => {
           actions.switch.toggle();
         }}>
             <Image mode='aspectFit'  className={styles.buttomBtnImage} src={oilSwitch ? power_on : power_off} />
              <Text className={styles.buttomBtnText}  style={{ color: oilSwitch ? '#66C2B9' : '#989FAF'}}>{Strings.getLang("str_switch")} </Text>
         </View>

         <View className={styles.buttomBtnLayout} onClick={() => {
             router.push('/quickTimer');
         }}>
             <Image mode='aspectFit'  className={styles.buttomBtnImage}  src={ ic_mode }  />
              <Text className={styles.buttomBtnText}>{Strings.getLang("str_mode")}</Text>
         </View>
      </View>
      <PickerOilPopup popShow={oilPiackerShow} onCancel={() => setOilPiackerShow(false)} onConfirm={onOilPiackerConfirm} />
      <PickerOilTypePopup popShow={aromatherapyShow} onCancel={() => setAromatherapyShow(false)} onConfirm={onAromatherapyConfirm} />
    </View>
  );
}

export default Home;
